#!/usr/bin/env python3
import os 
import sys 
import argparse 

def help():
    print("")

def append_cmd(cmd_dir, cmd_fn, cover=False, nocover=False):
    if os.path.isfile(cmd_fn):
        c = os.path.abspath(cmd_fn)
        if not os.access(c, os.X_OK):
            print("Error: %s is not executable" % c)
            return 
        c_ln = os.path.join(cmd_dir, os.path.basename(c))
        # 判断命令路径是否存在
        if os.path.exists(c_ln) and not cover:
            print("Warning: %s[%s] exists! Overwrite?"% (c_ln,os.readlink(c_ln)))
            if nocover or not input("[y/N] ").lower().startswith('y'):
                print("Abort")
                return
                # sys.exit(1)
            else:
                print("Overwrite %s" % c_ln)
                os.remove(c_ln)
            
        elif os.path.exists(c_ln) and cover:
            print("Overwrite %s[%s]" % (c_ln, os.readlink(c_ln)))
            os.remove(c_ln)
        # 创建软链接 
        os.symlink(c, c_ln)
        print(f'>>> append symbol link: {c_ln} -> {c}')
    else:
        print("Error: %s is not a valid file" % cmd_fn)
        return
    


def main():
    parser = argparse.ArgumentParser(description='Append command to a file')
    # command 是一个列表
    parser.add_argument('-c', '--command', help='Command to append', nargs='+', type=str)
    parser.add_argument( '--cover', action='store_true', dest='cover', help='Yes to all')
    parser.add_argument( '--nocover', action='store_true', dest='nocover', help='Yes to all')
    args = parser.parse_args()
    
    # 获取当本文件的路径
    cmd_dir = os.path.dirname(os.path.abspath(__file__))
    
    # 检查命令是否有可执行权限
    for c in args.command:
        if os.path.isdir(c):
            cs = os.listdir(c)
            for c_ in cs:
                append_cmd(cmd_dir, os.path.join(c, c_), args.cover, args.nocover)
                print()
        else:
            append_cmd(cmd_dir,c, args.cover, args.nocover)
        print()
if __name__ == '__main__':
    main()